import { Models } from '../../../../common/typings/model'
import KoaRouter from 'koa-router'
import Mysql from '../../../../core/Mysql'
import { Success } from '../../../../core/HttpException'
import validator from '../../../../middlewares/validator'
import Auth from '../../../../middlewares/Auth'
import editMenuById from '../../../../common/apiValidate/system/menu/edit'
import Config from '../../../../config/Config'

const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/menu`,
})

router.post('/edit', Auth.verifyTokenPermission, validator(editMenuById, 'body'), async (ctx: Models.Ctx) => {
  const {
    id,
    type,
    name,
    parentId,
    path = '',
    icon,
    serialNum,
    show,
    component = '',
    permission = '',
  } = ctx.request.body
  await Mysql.command(`
    UPDATE
      menu
    SET
      label = '${name}',
      type = ${type},
      parent_id = ${parentId},
      path = '${path}',
      icon = '${icon}',
      serial_num = ${serialNum},
      \`show\` = ${show},
      component = '${component}',
      permission = '${permission}'
    WHERE id = ${id}
  `)
  Auth.updateRedisRole()
  throw new Success()
})

export default router
